package dao.jpa;

import dao.TurmaDAO;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import modelo.Aluno;
import modelo.Disciplina;
import modelo.Turma;
import util.JPAUtil;

/**
 *
 * @author Jorge
 */
public class TurmaJpaDAO extends AbstractJpaDao<Turma, Long> implements TurmaDAO {

    public TurmaJpaDAO() {
        super(Turma.class);
    }

    @Override
    public List<Turma> getAll() {
        return JPAUtil.getEntityManager().createQuery("from Turma").getResultList();
    }

    public Turma getPorId(Long id) {
        String s = "select t from Turma t where t.id=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, id);

        try {
            return (Turma) query.getSingleResult();
        }
        catch (NoResultException e) {
            return null;
        }
    }

    public List<Turma> getDisponiveisPorAluno(Aluno aluno) {
        String s = "select t from Turma t where t not in " +
                "(select at.turma from AlunoTurma at where at.aluno=?)";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, aluno);

        return query.getResultList();
    }

    @Override
    public Turma getPorIdComListaAlunoTurmas(Long id) {
        String s = "select t from Turma t " +
                "left outer join fetch t.listaAlunoTurma at " +
                "left outer join fetch at.aluno " +
                "where t.id=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, id);

        return (Turma) query.getSingleResult();
    }

    @Override
    public List<Turma> getPorDisciplina(Disciplina disciplina) {
        String s = "select t from Turma t where t.disciplina=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, disciplina);

        try {
            return query.getResultList();
        }
        catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public List<Turma> getPorNomeDisciplina(String nomeDisciplina) {
        String s = "select t from Turma t where t.disciplina.nome=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, nomeDisciplina);

        try {
            return query.getResultList();
        }
        catch (NoResultException e) {
            return null;
        }
    }
}
